package com.flycent.hqhs.ui;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;

import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.Condition;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.AbsViewHolderAdapter;
import com.flycent.hqhs.ui.view.SimpleTitleBar;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;

/**
 * @author fbl
 *  筛选
 */
public class SearchConditionActivity extends BackableTitleBarActivity {
	@ViewInject(id = R.id.search_condition_list) ListView mList;

	private SearchConditionAdapter mAdapter;
	private String keyword = "";
	private String category = "";
	private List<Condition> mConditions;
	private String query;

	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		setContentView(R.layout.activity_search_condition);
		getTitleBar().setTitle(R.string.search_selection);
		FinalActivity.initInjectedView(this);

		keyword = getIntent().getStringExtra("keyword");
		category = getIntent().getStringExtra("category");
		mAdapter = new SearchConditionAdapter(this, R.layout.item_search_condition);
		mList.setAdapter(mAdapter);

		getCondition(keyword,category);

		mList.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent,
					View view, final int position, long id) {
				Condition mCondition = mAdapter.getData().get(position);
				String name = mCondition.getName() == null ? getNameString(mCondition.getId()+""):mCondition.getName();
				String [] aa = new String[mCondition.getOptions().size()];
				for (int i = 0; i < aa.length; i++) {
					aa[i] = mCondition.getOptions().get(i);
				}
				new AlertDialog.Builder(SearchConditionActivity.this).setTitle(name).setSingleChoiceItems(
								aa, 0,
								new DialogInterface.OnClickListener() {
									public void onClick(DialogInterface dialog, int which) {
										mConditions.get(position).setOptionid(which);
										dialog.dismiss();
										mAdapter.update(mConditions);
									}
								}).setNegativeButton("取消", null).show();
			}
		});
	}

	private void getCondition(final String str1, final String str2) {

		new Thread(){
			public void run() {
				try {
					mConditions = WebClient.getInstance(SearchConditionActivity.this).condition(str1, str2);
					mHandler.sendEmptyMessage(0);
				} catch (WebException e) {
					e.printStackTrace();
				}	
			};
		}.start();
	}

	@SuppressLint("HandlerLeak") 
	final Handler mHandler = new Handler(){
		public void dispatchMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				for (int i = 0; i < mConditions.size(); i++) {
					mConditions.get(i).getOptions().add(0, "全部");
				}
				mAdapter.update(mConditions);
				break;

			default:
				break;
			}
		};
	};

	private class SearchConditionAdapter extends AbsViewHolderAdapter<Condition>{

		public SearchConditionAdapter(Context context, int layoutRes) {
			super(context, layoutRes);
		}

		@Override
		protected void bindData(int pos, Condition itemData) {

			TextView text1 = getViewFromHolder(R.id.search_condition_text1);
			TextView text2 = getViewFromHolder(R.id.search_condition_text2);
//			List<String> mOptions = itemData.getOptions(); 
//			mOptions.add(0, "全部");
			
			int choiseid = itemData.getOptionid();
			text1.setText(itemData.getName() == null ? getNameString(itemData.getId()+""):itemData.getName());

			text2.setText(itemData.getOptions().get(choiseid).toString());
		}
	}
	//判断分类的名
	private String getNameString(String str){
		if("solr_price".equals(str)){
			return "价格";
		}else if ("solr_brand".equals(str)) {
			return "品牌";
		}else if ("solr_productCategory".equals(str)) {
			return "分类";
		}else {
			return str;
		}

	}
	
	@Override
	protected void onTitleBarCreated(SimpleTitleBar titleBar) {
		super.onTitleBarCreated(titleBar);
		titleBar.setRightButtonText(R.string.pay_method_sure);
		
		titleBar.setOnRightButtonClickListener(new OnClickListener() {
			@Override
			public void onClick(View paramView) {
				 
				 List<NameValuePair> params = new ArrayList<NameValuePair>();
				//	
				for (int i = 0; i < mConditions.size(); i++) {
					String ss = mConditions.get(i).getOptions().get(mConditions.get(i).getOptionid());
					if("全部".equals(ss)){
						ss = "";
					}
					params.add(new BasicNameValuePair(mConditions.get(i).getId(), ss));
				}
				HttpEntity reqEntity = null;
				try {
					reqEntity = new UrlEncodedFormEntity(params, "utf-8");
				   query = EntityUtils.toString(reqEntity);
				} catch (ParseException | IOException e) {
					e.printStackTrace();
				}
				
				Intent intent = new Intent();
				intent.putExtra("conditions", query);
				setResult(300,intent);
				finish();
			}
		});
		
	}



}
